import {getToken, setToken, removeToken} from "@/utils/auth";
import {userLogin, userLogout} from "@/api/common_api";

const state = {
    token: getToken(),
    name: '',
    avatar: ''
}

const mutations = {
    SET_TOKEN: (state, token) => {
        state.token = token
    },
    SET_NAME: (state, name) => {
        state.name = name
    },
    SET_AVATAR: (state, avatar) => {
        state.avatar = avatar
    }
}

const actions = {
    // 在store里登录，由于采用cookie缓存的token，所以无需另外存储token。
    // 登录成功则保存账号名，登录失败返回错误信息
    async login({commit}, userInfo) {
        const {account, password} = userInfo
        const result = await userLogin(account, password)
        const loginStatus = result.data.status
        commit('SET_NAME', '')
        //登录成功
        if (loginStatus === 1) {
            commit('SET_NAME', account)
            setToken('')
            return null
        }
        //登录失败，抛出异常
        throw {msg:result.data.message}
    },
    async logout({commit}) {
        await userLogout();
        commit('SET_NAME', '')
        commit('SET_TOKEN', '')
        removeToken()
    }
}

export default {
    namespaced: true,
    state,
    actions,
    mutations
}